package com.hgyc.mom.common.util;

import com.hgyc.mom.common.enums.PeriodTypeEnum;

/**
 * 根据周期和频率动态生成cron表达式
 * @author  fwj
 * @since 2025-08-15
 */
public class CronExpressionUtils {

    public static String generate(PeriodTypeEnum periodType, int cycleType, int hour, int minute, Integer weekDay, Integer dayOfMonth) {
        switch (periodType) {
            case DAY:
                // 每 N 天一次
                return String.format("0 %d %d 1/%d * ?", minute, hour, cycleType);

            case WEEK:
                // 每 N 周一次（Quartz 不直接支持每 N 周，所以这里 weekDay 决定哪天执行）
                String weekStr = weekDay != null ? weekDayToQuartz(weekDay) : "MON";
                return String.format("0 %d %d ? * %s", minute, hour, weekStr);

            case MONTH:
                // 每 N 个月一次
                int dom = (dayOfMonth != null) ? dayOfMonth : 1;
                return String.format("0 %d %d %d 1/%d ?", minute, hour, dom, cycleType);

            case QUARTER:
                // 季度执行（1,4,7,10 月等）
                dom = (dayOfMonth != null) ? dayOfMonth : 1;
                String quarterMonths = getQuarterMonths(cycleType);
                return String.format("0 %d %d %d %s ?", minute, hour, dom, quarterMonths);

            case YEAR:
                // 每年执行一次（或每年指定月执行）
                dom = (dayOfMonth != null) ? dayOfMonth : 1;
                return String.format("0 %d %d %d 1 ?", minute, hour, dom);

            default:
                throw new IllegalArgumentException("未知周期类型: " + periodType);
        }

    }

    private static String weekDayToQuartz(int weekDay) {
        switch (weekDay) {
            case 1: return "SUN";
            case 2: return "MON";
            case 3: return "TUE";
            case 4: return "WED";
            case 5: return "THU";
            case 6: return "FRI";
            case 7: return "SAT";
            default: return "MON";
        }
    }

    private static String getQuarterMonths(int cycleType) {
        if (cycleType <= 1) {
            return "1,4,7,10"; // 每季度一次
        }
        if (cycleType == 2) {
            return "1,7"; // 每半年一次
        }
        return "1"; // 每年一次
    }
}
